package com.rsscollector.controller.admin.action;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.ee.servlet.QuartzInitializerServlet;

import com.rsscollector.util.QuartzUtil;

public class ListJobsAction extends Action {

	public static Logger logger = Logger.getLogger(ListJobsAction.class
			.getName());

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// Get Scheduler object 
		ServletContext context = this.getServlet().getServletContext();
		SchedulerFactory schedulerFactory = (SchedulerFactory) context
				.getAttribute(QuartzInitializerServlet.QUARTZ_FACTORY_KEY);
		Scheduler scheduler = schedulerFactory.getScheduler();
		
		// Get list of jobs in this Scheduler
		List<JobDetail> jobList = QuartzUtil.getJobs(scheduler);

		// Create a map (JobDetail, List<Trigger>) to be displayed on JSP page
		Map<JobDetail, List<Trigger>> job2Triggers = new LinkedHashMap<JobDetail, List<Trigger>>();
		for (JobDetail jobDetail : jobList) {
			List<Trigger> triggers = QuartzUtil.getTriggersFromJob(scheduler, jobDetail);
			job2Triggers.put(jobDetail, triggers);
		}
		
		request.setAttribute("job2Triggers", job2Triggers);

		return mapping.findForward("success");
	}

}
